/**
 * 登录 create to by doujiabao
 */

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { updateUserInfo } from '@/action'

import styles from './index.module.styl'

import fetch from '@/service/fetch'
import Cookies from 'js-cookie'
import routesMap from '@/router'

import { Form, Input, Button } from 'antd'

const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
}
const tailLayout = {
    wrapperCol: { offset: 6, span: 14 },
}

class Login extends Component {

    state = {
        loading: false
    }

    //登录
    onFinish = (values) => {
        //每次登录清空login
        if (Cookies.get('d_logintoken')) Cookies.remove('d_logintoken')
        //...
        this.setState({
            loading: true
        }, () => {
            fetch.login({
                userAccount: values.userAccount,
                userPassword: values.userPassword
            }).then(res => {
                Cookies.set('userInfo', JSON.stringify(res.data[0]))
                //...
                this.setState({ loading: false }, () => {
                    //redux
                    this.props.updateUserInfo(res.data[0])
                    //loginstats
                    this.props.login()
                    //跳转至首页
                    window.location.href = `${window.location.origin + window.location.pathname}#${routesMap.dashboard}`
                })
            }).catch(err => {
                this.setState({ loading: false })
            })
        })
    }

    render() {

        const {
            loading
        } = this.state

        return (<div className={styles.loginBox}>
            <div className={styles.login}>
                <h2 className={styles.title}>blog-admin</h2>
                <Form
                    {...layout}
                    name="basic"
                    onFinish={this.onFinish}
                >
                    <Form.Item
                        label="账号"
                        name="userAccount"
                        rules={[{ required: true, message: '请输入账号!' }]}
                    >
                        <Input allowClear />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="userPassword"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input.Password allowClear />
                    </Form.Item>

                    <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType='submit' loading={loading}>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>)
    }

}

const mapDispatchToProps = dispatch => {
    return {
        updateUserInfo(data) {
            dispatch(updateUserInfo(data))
        }
    }
}

export default connect(null, mapDispatchToProps)(Login)